<?php
namespace Api\Controller;

class OrderController extends APIController{

    protected $tbName = CONTROLLER_NAME;

    /*待验证的参数*/
    public $tca = [
        'user_id' => [
            'method'    => 'exists',
            'model'     => 'member',
            'code_key'  => 'lawless'
        ],
        'status' => [
            'method'    => 'regex',
            'model'     => '/^[0-5]$/',
            'code_key'  => 'lawless'
        ]
    ];

    /**
     * 用户订单列表
     */
     public function index(){
        try{
            $this->safeChecked();
             /*验证*/
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $user_id = I('param.user_id');
            $status = I('param.status');
            $where['a.deleted'] = 0;
            $where['a.user_id'] = $user_id;
            if($status){
                $where['a.status'] = $status;
            }
            $page = I('param.page',C('PAGE'));
            $show_num = I('param.show_num',C('SHOW_NUM'));
            $Obj = D($this->tbName); //实例化对象
            $list = $Obj
                    ->alias('a')
                    ->join(C('DB_PREFIX').'goods as b ON a.goods_id = b.id')
                    ->where($where)
                    ->Field('a.id,a.order_num,a.num,a.status,a.pay_price,a.goods_name,a.assistant,a.deal_money,b.image,b.crdate')
                    ->order('a.crdate desc')
                    ->limit(($page-1)*$show_num,$show_num)
                    ->select();
            if($list){
                foreach ($list as $key => &$value) {
                    $value['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$value['crdate']).'/'.$value['image'];
                }
            }
            $this->res_data['data'] = $list?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
     }
    /**
     * 订单详情
     */
    public function orderInfo(){
        try{
            $this->safeChecked();
            $this->tca = array(
                'order_id' =>array(
                    'method' => 'exists',
                    'model' => 'Order',
                    'code_key' => 'lawless'
                )
            );
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $order_id = I('param.order_id');
            $Obj = D($this->tbName);
            /*订单数据*/
            $order = $Obj
                    ->alias('a')
                    ->join(C('DB_PREFIX').'goods as b ON a.goods_id = b.id')
                    ->where(array('a.id' => $order_id))
                    ->field('a.id,a.status,a.pay_price,a.goods_id,a.goods_name,a.assistant,a.order_num,a.crdate,a.num,a.name,a.phone,a.address,a.deal_money,a.group_id,a.postage_num,b.image,b.crdate as createtime')
                    ->select();
            $order = current($order);
            $order['crdate'] = date('Y-m-d H:i:s',$order['crdate']);
            $order['image'] = C('DOMAIN_URL').C('PATH_UPLOAD').'Goods/'.date('Ym',$order['createtime']).'/'.$order['image'];
            //拼团信息
            //团长
            $leader = M('group')
                    ->alias('a')
                    ->join(C('DB_PREFIX').'member as b ON a.user_id = b.id')
                    ->where(array('a.id' => $order['group_id']))
                    ->Field('a.num,a.expired,a.complete_time,b.id,b.wxlogo')
                    ->select();
            $leader = current($leader);
            //参团人员
            $group_followers = $Obj
                            ->alias('a')
                            ->join(C('DB_PREFIX').'member as b ON a.user_id = b.id')
                            ->where(array('a.group_id' => $order['group_id'],'a.user_id' => ['neq',$leader['id']]))
                            ->field('b.wxlogo')
                            ->select();
            $group_info = [$leader['wxlogo']];
            if($group_followers){
                $group_info = array_map(function($value){
                    return $group_info[] = $value['wxlogo'];
                }, $group_followers);
            }
            if($leader['complete_time'] > 0){
                $order['group_status'] = '拼团成功';
            }else{
                if($leader['expired'] > time()){
                    $order['group_status'] = '待成团';
                }else{
                  $order['group_status'] = '拼团失败';  
                }
            }
            $order['group_num'] = $leader['num'];
            $order['group_info'] = $group_info;
            $this->res_data['data'] = $order;
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }
    /**
     * 订单取消
     */
    public function cancelOrder(){
        $this->safeChecked();
        $model = new \Think\Model;
        $model->startTrans();
        try{
            $this->tca = array(
                'order_id' =>array(
                    'method' => 'exists',
                    'model' => 'Order',
                    'code_key' => 'lawless'
                )
            );
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $order_id = I('param.order_id');
            $Obj = D($this->tbName);
            $info = $Obj->find($order_id);
            if(!in_array($info['status'],[1,2])){
                $this->res_data['code_key'] = 'order_status_error';
                $this->apiReply();
            }
            $param['tstamp'] = time();
            if($info['status'] == 1){
                $param['status'] = 6;
            }else{
                $param['status'] = 8;
            }
            $num = $Obj->where(array('id' => $order_id))->save($param);
            if(!$num){
                debug('取消订单失败');
                debug($Obj->_sql());
                $model->rollback();
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            $model->commit();
        }catch(\Exception $e){
            debug([$e->getmessage(),$e->getfile(),$e->getline()]);
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 确定收货
     */
    public function makesure(){
       $this->safeChecked();
        $model = new \Think\Model;
        $model->startTrans();
        try{
            $this->tca = array(
                'order_id' =>array(
                    'method' => 'exists',
                    'model' => 'Order',
                    'code_key' => 'lawless'
                )
            );
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $order_id = I('param.order_id');
            $Obj = D($this->tbName);
            $info = $Obj->find($order_id);
            if($info['status'] != 3){
                $this->res_data['code_key'] = 'order_status_error';
                $this->apiReply();
            }
            $param = [
                'tstamp' => time(),
                'status' => 4
            ];
            $num = $Obj->where(array('id' => $order_id))->save($param);
            if(!$num){
                debug('确认收货失败');
                debug($Obj->_sql());
                $model->rollback();
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            $model->commit();
        }catch(\Exception $e){
            debug([$e->getmessage(),$e->getfile(),$e->getline()]);
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 订单
     * 根据是否传入group_id判断为参团订单还是开团订单
     */
    public function createOrder(){
        try{
            $this->safeChecked();
            /*基础验证*/
            $check = D('Validate','Util');
            $this->tca = array(
                'user_id' => array('method' => 'exists','model' => 'member','code_key' => 'lawless'),
                'goods_id' => array('method' => 'exists','model' => 'goods','code_key' => 'lawless'),
                'goods_name' => array('method' => 'regex','model' => '/\S/','code_key' => 'lawless'),
                'goods_info_id' => array('method' => 'exists','model' => 'goods_info','code_key' => 'lawless'),
                'num' => array('method' => 'regex','model' => '/^[1-9]\d*$/','code_key' => 'lawless'),
                'name' => array('method' => 'regex','model' => '/\S/','code_key' => 'lawless'),
                'phone' => array('method' => 'regex','model' => '/^1[3|4|5|7|8|9]\d{9}/','code_key' => 'lawless'),
                'address' => array('method' => 'regex','model' => '/\S/','code_key' => 'lawless'),
                'user_coupon_id' => array('method' => 'regex','model' => '/\\d/','code_key' => 'lawless'),
                'coupon_money' => array('method' => 'regex','model' => '/\\d/','code_key' => 'lawless'),
                'activity_id' => array('method' => 'exists','model' => 'activity','code_key' => 'lawless'),
                'group_id' => array('method' => 'regex','model' => '/\\d/','code_key' => 'lawless'),
                'pay_money' => array('method' => 'regex','model' => '/^[0-9]+(.[0-9]{1,2})?$/','code_key' => 'lawless'),
            );
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $data = I('param.');
            //商品总额 
            $total_price = 0.00;
            $Activity = M('activity');
            //获取购买商品对应的团购价
            $info  = $Activity
                    ->alias('a')
                    ->join(C('DB_PREFIX').'plan as b ON b.activity_id = a.id')
                    ->where(array('a.id' => $data['activity_id'],'b.goods_info_id' => $data['goods_info_id'],'b.deleted' => 0))
                    ->Field('a.id,a.hidden,a.type,a.end,a.num,a.limit,a.total,a.is_support_coupon,a.group_coupon_id,a.coupon_id,a.cut_money,a.expired,a.auto_group,b.group_price,b.leader_price')
                    ->select();
            if(!$info){
                $this->res_data['code_key'] = 'lawless';
                $this->apiReply();
            }
            $info = current($info);
            if($info['end'] < time()){
                $this->res_data['code_key'] = 'activity_over'; //活动已结束
                $this->apiReply();
            }
            //活动购买数量验证
            if($info['limit'] > 0){
                //本次购买
                if($info['limit'] < $data['num']){
                    $this->res_data['code_key'] = 'over_activity_limit'; //超过活动限制购买数量
                    $this->apiReply();
                }
                //多次购买,只计算下单的商品总数 不考虑下单未支付或者支付后申请退款的情况
                $count = $Activity
                        ->alias('a')
                        ->join(C('DB_PREFIX').'group as b ON b.activity_id = a.id')
                        ->join(C('DB_PREFIX').'order as c ON c.group_id = b.id')
                        ->where(array('a.id' => $data['activity_id'],'c.user_id' => $data['user_id'],'c.goods_id' => $data['goods_id']))
                        ->sum('num');
                $count = $count?:0;
                if($info['limit'] < ($data['num'] + $count)){
                    $this->res_data['code_key'] = 'over_activity_limit'; //超过活动限制购买数量
                    $this->apiReply();
                }
            }
            //活动库存验证
            //该活动总的销售量(计算订单状态为非取消,非申请退款的订单商品总数)
            $total_sales = $Activity
                    ->alias('a')
                    ->join(C('DB_PREFIX').'group as b ON b.activity_id = a.id')
                    ->join(C('DB_PREFIX').'order as c ON c.group_id = b.id')
                    ->where(array('a.id' => $data['activity_id'],'c.goods_id' => $data['goods_id'],'c.status' => ['elt',5]))
                    ->sum('num');
            $total_sales = $total_sales?:0;
            if($info['total'] < ($total_sales + $data['num'])){
                $this->res_data['code_key'] = 'stock_not_enough';
                $this->apiReply();
            }

            //针对商品规格库存
            //获取商品总库存
            $total_stock = M('goods_info')->where(array('id' => $data['goods_info_id']))->getField('stock');
            //获取订单占用库存数
            $order_free_stock = M('order')->where(array('goods_info_id' => $goods_info_id,'status' => array('IN',array(1,2))))->sum('num');
            $usable_stock = $total_stock - $order_free_stock;
            if($usable_stock < $data['num']){
                $this->res_data['code_key'] = 'stock_not_enough';
                $this->apiReply();
            }

            //若为神秘团 且为参团订单 验证是否为新用户(根据订单数来判断,只存在下单未支付的订单判断为老用户)
            if($info['type'] == 2 && $data['group_id'] != 0){
                $count = M('order')->where(array('user_id' => $data['user_id']))->count();
                if($count > 0){
                    $this->res_data['code_key'] = 'user_not_exists';
                    $this->apiReply();
                }
            }

            //运费
            $Goods = M('goods');
            $goods_info = $Goods->find($data['goods_id']);
            $postage_price = $goods_info['postage_price'] * $data['num'];
            //判断订单为参团订单还是开团订单 0为开团订单 1为参团订单
            $other_money = 0;
            if($data['group_id'] == 0){
                if($info['type'] == 2){
                    $goods_price = $info['leader_price'];
                }else{
                    $goods_price = $info['group_price'];
                    $other_money = $info['cut_money'];
                }
            }else{
                $goods_price = $info['group_price'];
                //判断用户是否已经参与过该团
                $count = M($this->tbName)->where(array('group_id' => $data['group_id'],'user_id' => $data['user_id']))->count()?:0;
                if($count){
                    $this->res_data['code_key'] = 'just_one_time'; //已经参加过了
                    $this->apiReply();
                }
                //判断是否订单数量是否已经到达满团数量
                $order_count = M($this->tbName)->where(array('group_id' => $data['group_id']))->count();
                if($info['num'] <= $order_count){
                    $this->res_data['code_key'] = 'is_full_member';
                    $this->apiReply();
                }
            }
            $total_price = $goods_price * $data['num'];
            $pay_money = $total_price - $other_money;
            $coupon_money = 0;
            if($data['user_coupon_id']){
                $coupon = D('UserCoupon');
                $usable_coupon = $coupon->visiableCoupon($data['user_id'],$pay_money,$data['goods_id']);
                if(!$usable_coupon){
                    $this->res_data['code_key'] = 'lawless';
                    $this->apiReply();
                }
                $coupon_id = array();
                foreach($usable_coupon as $value){
                    $coupon_id[] = $value['id'];
                }
                if(!in_array($data['user_coupon_id'],$coupon_id)){
                    $this->res_data['code_key'] = 'lawless';
                    $this->apiReply();
                }
                $coupon_money = $usable_coupon[array_search($data['user_coupon_id'],$coupon_id)]['money'];
            }
            
            //计算支付金额 
            $pay_price = round(($pay_money - $coupon_money),2);
            if($pay_price < 0){
                $pay_price = 0.01;
            }
            //订单数据保存
            $order = M($this->tbName);
            $order->startTrans();
            $new_group = false;
            //是否为新开团
            if($data['group_id'] == 0){
                $now_time =  time();
                $expired = $info['expired'] * 60 * 60 + $now_time;
                $group_data = [
                    'activity_id' => $info['id'],
                    'type' => $info['type'],
                    'limit' => $info['limit'],
                    'num' => $info['num'],
                    'auto_group' => $info['auto_group'],
                    'group_num' => date('YmdHis').$this->createRandomStr(),
                    'user_id' => $data['user_id'],
                    'goods_id' => $data['goods_id'],
                    'goods_name' => $goods_info['name'],
                    'crdate' => $now_time
                ];
                $id = M('group')->add($group_data);
                if(!$id){
                    debug('创建团信息失败');
                    debug(M('group')->_sql());
                    $order->rollback();
                    $this->res_data['code_key'] = 'fail';
                    $this->apiReply();
                }
                $data['group_id'] = $id;
                $new_group = true;
            }
            $goods = M('goods_info')->find($data['goods_info_id']);
            //创建订单数据
            $order_data = array(
                'group_id' => $data['group_id'],
                'order_num' => $this->Config['order_prefix'].date('YmdHis').$this->createRandomStr(),
                'user_id' => $data['user_id'],
                'name' => $data['name'],
                'phone' => $data['phone'],
                'address' => $data['address'],
                'total_price' => $total_price,
                'user_coupon_id' => $data['user_coupon_id']?:0,
                'coupon_money' => $coupon_money,
                'pay_price' => $pay_price,
                'goods_id' => $data['goods_id'],
                'goods_name' => $goods_info['name'],
                'goods_info_id' => $data['goods_info_id'],
                'assistant' => $goods['assistant'],
                'sku' => $goods['sku'],
                'deal_money' => $goods_price,
                'cost_money' => $goods['cost_price'],
                'distribution_money' => $goods['distribution_price'],
                'num' => $data['num'],
                'postage_money' => $postage_price,
                'crdate' => time(),
                'tstamp' => time()
            );
            $order_id = $order->add($order_data);
            if(!$order_id){
                debug('创建订单失败');
                debug($order->_sql());
                $order->rollback();
                $this->res_data['code_key'] = 'fail';
                $this->apiReply();
            }
            $result = array(
                'order_num' => $order_data['order_num'],
                'group_id' => $data['group_id']
                );
            //推送订单至异步处理
            /*$url = 'http://www.pingecai.com/api/index/doRequest';
            $data = ['id' => $order_id];
            syncRequest($url,$data,'post');*/
            $order->commit();
            $this->res_data['data'] = $result;
        }catch(\Exception $e){
            debug([$e->getmessage(),$e->getline(),$e->getfile()]);
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
    }

    /**
     * 不同状态的订单数量统计
     */
     public function statisticsOrder(){
        try{
            $this->safeChecked();
            $this->tca = array(
                'user_id' =>array(
                    'method' => 'exists',
                    'model' => 'Order',
                    'code_key' => 'lawless'
                )
            );
             /*验证*/
            $check = D('Validate','Util');
            $result = $check->letParam($this->tca)->response();
            if(isset($result['return_msg'])){
                $this->res_data['code_key'] = $result['return_msg'];
                $this->apiReply();
            }
            $user_id = I('param.user_id');
            $status = 1;
            static $data = [];
            $Obj = M($this->tbName); //实例化对象
            while($status < 5){
                $data[] = $Obj->where(array('user_id' => $user_id,'status' => $status))->count()?:0;
                ++$status;
            }
            $this->res_data['data'] = $data?:array();
        }catch(\Exception $e){
            debug($e->getmessage());
            $this->res_data['code_key'] = 'fail';
        }
        $this->apiReply();
     }
    
}